
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Helper;
using IRepository;
using Models;
using System.Linq;
using Models.Entity;
using MySql.Data.MySqlClient;
using Dapper;
using System.Data;
using System.Linq.Expressions;

namespace Repository
{
    /// <summary>
    /// 图片处理服务
    /// </summary>
    public class TeacherRepository : ITeacherRepository
    {
        DapperHelper<CTeacherEntity> dbHelper = new DapperHelper<CTeacherEntity>();
        DapperHelper<CTeacherCourseEntity> dbHelper_teacherCourse = new DapperHelper<CTeacherCourseEntity>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        public async Task<CTeacherEntity> Single(DtoDo<int> inObj)
        {
            var ent = await dbHelper.Single(x => x.teacher_id == inObj.Key);
            if (ent == null) return null;
            ent.courseList = new List<CTeacherCourseEntity>();
            //查找该配置的所有
            foreach (var item in await dbHelper_teacherCourse.FindAll(X => X.teacher_id == ent.teacher_id))
            {
                ent.courseList.Add(item);
            }
            return ent;
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key">主键 ID</param>
        /// <returns></returns>
        public async Task<ResultObj<int>> Delete(int key)
        {
            ResultObj<int> reObj = new ResultObj<int>();
            try
            {
                string sqlStr = $"select count(1) from c_classes_cfg_teacher a,c_teacher_course b where a.teacher_course_id=b.teacher_course_id and b.teacher_id={key}";
                if (Convert.ToInt32(await dbHelper.ExecuteScalarAsync(sqlStr)) > 0)
                {
                    throw new Exception("在有配置里要删除的课程");
                }
                sqlStr = $"select count(1) from c_week_course a,c_teacher_course b where a.teacher_course_id=b.teacher_course_id and b.teacher_id={key}";
                if (Convert.ToInt32(await dbHelper.ExecuteScalarAsync(sqlStr)) > 0)
                {
                    throw new Exception("在当前课表里有要删除的课程");
                }

                reObj.data = await dbHelper_teacherCourse.Delete(i => i.teacher_id == key);
                reObj.success = reObj.data > 0;

                reObj.data = await dbHelper.Delete(i => i.teacher_id == key);
                reObj.success = reObj.data > 0;

            }
            catch (System.Exception e)
            {
                reObj.success = false;
                reObj.msg = e.Message;
            }

            return reObj;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="inEnt"></param>
        /// <returns></returns>
        public async Task<ResultObj<int>> Save(DtoSave<CTeacherEntity> inEnt)
        {

            ResultObj<int> reObj = new ResultObj<int>();
            if (inEnt.data.courseList == null) inEnt.data.courseList = new List<CTeacherCourseEntity>();
            DapperHelper<CTeacherEntity> _dbHelper = new DapperHelper<CTeacherEntity>();
            _dbHelper.TranscationBegin();
            try
            {
                DapperHelper<CTeacherCourseEntity> _dbHelper_teacherCourse = new DapperHelper<CTeacherCourseEntity>(_dbHelper.GetConnection(), _dbHelper.GetTransaction());
                if (inEnt.data.teacher_id == 0) //添加
                {
                    //判断教师是否存在
                    if ((await _dbHelper.Count(x => x.name == inEnt.data.name)) > 0)
                    {
                        throw new Exception("不可重复添加");
                    }
                    else
                    {
                        inEnt.data.teacher_id = await SequenceRepository.GetNextID<CTeacherEntity>();
                        reObj.data = await _dbHelper.Save(inEnt);
                        reObj.success = reObj.data > 0;
                        if (reObj.success)
                        {
                            if (inEnt.data.courseList.Count() > 0)
                            {
                                foreach (var item in inEnt.data.courseList)
                                {
                                    item.teacher_id = inEnt.data.teacher_id;
                                }
                                reObj.success = (await _dbHelper_teacherCourse.Saves(new DtoSave<List<CTeacherCourseEntity>>
                                {
                                    data = inEnt.data.courseList
                                })) > 0;
                                if (!reObj.success)
                                {
                                    throw new Exception("保存课程失败");
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("保存课程失败");
                        }
                    }
                }
                else //修改
                {
                    reObj.data = await _dbHelper.Update(inEnt);
                    reObj.success = reObj.data > 0;
                    if (!reObj.success)
                    {
                        throw new Exception("修改教师失败");
                    }
                    else
                    {
                        foreach (var item in inEnt.data.courseList)
                        {
                            item.teacher_id = inEnt.data.teacher_id;
                        }
                        // 数据库里的课程
                        var nowCourseList=await _dbHelper_teacherCourse.FindAll(x => x.teacher_id == inEnt.data.teacher_id);
                        // 数据库里的课程ID
                        var nowCourseIdList = nowCourseList.Select(x => x.course_id).ToList();
                        // 要保存的课程
                        var saveCourseIdList = inEnt.data.courseList.Select(x => x.course_id).ToList();
                        // 待删除的
                        var delList = nowCourseIdList.Where(x => !saveCourseIdList.Contains(x)).ToList();
                        // 待更新的
                        var updateIdList = saveCourseIdList.Where(x => nowCourseIdList.Contains(x)).ToList();
                        // 待不回的
                        var addIdList = saveCourseIdList.Where(x => !nowCourseIdList.Contains(x)).ToList();

                        // 删除课程
                        if (delList.Count() > 0)
                        {
                            string sqlStr = $"select count(1) from c_classes_cfg_teacher a,c_teacher_course b where a.teacher_course_id=b.teacher_course_id and b.teacher_id={inEnt.data.teacher_id} and b.course_id in ({string.Join(",", delList)})";
                            if (Convert.ToInt32(await _dbHelper.ExecuteScalarAsync(sqlStr)) > 0)
                            {

                                sqlStr=$"delete from c_classes_cfg_teacher_classes where teacher_cfg_id in (select teacher_cfg_id from c_classes_cfg_teacher a,c_teacher_course b where a.teacher_course_id=b.teacher_course_id and b.teacher_id={inEnt.data.teacher_id} and b.course_id in ({string.Join(",", delList)}))";
                                await _dbHelper.Exec(sqlStr);
                                sqlStr=$"delete from c_classes_cfg_teacher where  teacher_course_id in (select teacher_course_id from  c_teacher_course where teacher_id={inEnt.data.teacher_id} and b.course_id in ({string.Join(",", delList)}))";
                                await _dbHelper.Exec(sqlStr);

                                throw new Exception("在有班级配置了该课程");
                            }
                            sqlStr = $"select count(1) from c_week_course a,c_teacher_course b where a.teacher_course_id=b.teacher_course_id and b.teacher_id={inEnt.data.teacher_id} and b.course_id in ({string.Join(",", delList)})";
                            if (Convert.ToInt32(await _dbHelper.ExecuteScalarAsync(sqlStr)) > 0)
                            {
                                throw new Exception("在当前课表里有要删除的课程");
                            }
                            reObj.success = (await _dbHelper_teacherCourse.Delete($"course_id in ({string.Join(",", delList)}) and teacher_id={inEnt.data.teacher_id}")) > 0;
                            if (!reObj.success)
                            {
                                throw new Exception("删除课程失败");
                            }
                        }

                        // 待更新的
                        if (updateIdList.Count() > 0)
                        {
                            foreach (var item in updateIdList)
                            {
                                reObj.success = (await _dbHelper_teacherCourse.Update(new DtoSave<CTeacherCourseEntity>
                                {
                                    data = inEnt.data.courseList.SingleOrDefault(x => x.course_id == item),
                                    saveFieldListExp = x => new object[] { x.course_id, x.place_id, x.together_num,x.no_course },
                                    whereListExp = x => new object[] { x.course_id, x.teacher_id }
                                })) > 0;
                                if (!reObj.success)
                                {
                                    throw new Exception($"更新课程ID[{item}]失败");
                                }
                            }
                        }

                        // 待添加的
                        if (addIdList.Count() > 0)
                        {
                            var saveList = inEnt.data.courseList.Where(x => addIdList.Contains(x.course_id)).ToList();
                            foreach (var item in saveList)
                            {
                                item.teacher_course_id = await SequenceRepository.GetNextID<CTeacherCourseEntity>();
                            }
                            reObj.success = (await _dbHelper_teacherCourse.Saves(new DtoSave<List<CTeacherCourseEntity>>
                            {
                                data = inEnt.data.courseList.Where(x => addIdList.Contains(x.course_id)).ToList(),
                            })) > 0;

                            if (!reObj.success)
                            {
                                throw new Exception($"批量更新课程失败");
                            }
                        }
                    }
                }

                _dbHelper.TranscationCommit();
                reObj.success = true;

            }
            catch (System.Exception e)
            {
                _dbHelper.TranscationRollback();
                LogHelper.WriteErrorLog<TeacherRepository>("保存教师出错", e);
                reObj.success = false;
                reObj.msg = e.Message;
            }
            return reObj;
        }
    }
}
